package cn.fanyc.action.blockchain.fbc.org1.controller.issue;

import cn.fanyc.anvil.sdk.common.domain.RestDomain;
import cn.fanyc.action.blockchain.fbc.org1.config.GlobalConstants;
import org.hyperledger.fabric.gateway.Contract;
import org.hyperledger.fabric.gateway.ContractException;
import org.hyperledger.fabric.gateway.Gateway;
import org.hyperledger.fabric.gateway.Network;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.concurrent.TimeoutException;

/**
 * 账号管理控制器
 *
 * @author Fanyc
 * @date 2020/6/18 13:59
 */
@RestController
@RequestMapping("/issue")
public class IssueController {

    /**
     * 日志记录器
     */
    private final Logger logger = LoggerFactory.getLogger(IssueController.class);

    /**
     * Fabric网关
     */
    @Autowired
    private Gateway gateway;

    /**
     * 发布票据
     *
     * @param issuer      发布者
     * @param paperNumber 票据号
     * @param faceValue   面额
     * @param maturity    周期
     * @return 发布结果
     */
    @RequestMapping("/send")
    public RestDomain<?> send(String issuer, String paperNumber, String faceValue, int maturity) {
        logger.info("==========发布票据：发布者={}，票据号={}, 面额={}，周期={}==========", issuer, paperNumber, faceValue, maturity);
        try {
            // get the network and contract
            Network network = gateway.getNetwork(GlobalConstants.CHANNEL_NAME);

            Contract contract = network.getContract(GlobalConstants.CONTRACT_FBC);

            Calendar instance = GregorianCalendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String issueDateTime = sdf.format(instance.getTime());
            instance.add(Calendar.DAY_OF_MONTH, maturity);
            String maturityDateTime = sdf.format(instance.getTime());

            byte[] issues = contract.submitTransaction("issue", issuer, paperNumber, issueDateTime, maturityDateTime, faceValue);
            System.out.println(new String(issues));
        } catch (InterruptedException | TimeoutException | ContractException e) {
            e.printStackTrace();
        }
        logger.info("==========发布完成==========");
        return RestDomain.success();
    }
}
